package com.example;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

public class ThreadCreateByFutureTask {

    public static class TestTask implements Callable<String>{

        @Override
        public String call() throws Exception {
            long start = System.currentTimeMillis();
            while (!Thread.currentThread().isInterrupted()){
                System.out.println("我是" + Thread.currentThread().getName());
            }
            long end = System.currentTimeMillis();
            long cost = (end - start) / 1000;
            return "运行时长：" + cost + "秒";
        }

        public static void main(String[] args) throws InterruptedException, ExecutionException {
            FutureTask<String> futureTask = new FutureTask(new TestTask());
            Thread testThread = new Thread(futureTask, "test-thread");
            testThread.start();

            Thread thread3 = new Thread(()->{
                try {
                    String result = futureTask.get();
                    System.out.println("futureTask.get()返回：" + result);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                }
            }, "thread3");
            thread3.start();


            Thread.sleep(1000*5);
            System.out.println("thread3的状态：" + thread3.getState());


            testThread.interrupt();
        }
    }
}
